<template>
    <div>
        <div><h1>商品列表</h1></div>
        <div>
            <el-form
                :inline="true"
                :model="searchForm"
                class="demo-form-inline"
            >
                <el-form-item label="关键字">
                    <el-input
                        v-model="searchForm.keyWord"
                        placeholder="请输入关键字"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="ID">
                    <el-input
                        v-model="searchForm.id"
                        placeholder="请输入商品ID"
                        clearable
                    />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="onQuery">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-button type="primary" @click="handleAddProd"
                >添加商品</el-button
            >
            <el-button type="danger" @click="handleDeleteAll"
                >批量删除</el-button
            >
        </div>
        <div>
            <el-table
                :data="prodList"
                stripe
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="prodId" label="ID" width="80" />
                <el-table-column prop="prodSpu" label="SPU" width="100" />
                <el-table-column prop="prodName" label="名称" width="100" />
                <el-table-column prop="typeName" label="类型" width="100" />
                <el-table-column prop="brandName" label="品牌" width="100" />
                <el-table-column prop="unitName" label="单位" width="100" />
                <el-table-column prop="tagName" label="标签" width="100" />
                <el-table-column prop="apprName" label="供应商" width="180" />
                <el-table-column label="图片">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.prodImage != null"
                            :src="scope.row.prodImage"
                            style="width: 50px; height: 50px"
                        ></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="prodStatus" label="状态" width="120">
                    <template #default="scope">
                        <el-tag v-if="scope.row.prodStatus == 0">未上架</el-tag>
                        <el-tag type="success" v-if="scope.row.prodStatus == 1"
                            >已上架</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column prop="kindName" label="种类" width="120" />
                <el-table-column prop="createTime" label="时间" width="180" />
                <el-table-column label="操作" width="280">
                    <template #default="scope">
                        <el-button
                            size="small"
                            type="primary"
                            @click="handleBuyProd(scope.row)"
                        >
                            购买
                        </el-button>
                        <el-button
                            size="small"
                            type="primary"
                            @click="handleProd(scope.row)"
                        >
                            商品
                        </el-button>
                        <el-button
                            size="small"
                            type="success"
                            @click="handleAtta(scope.row)"
                        >
                            商品附件
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="margin-top: 20px">
            <el-pagination
                v-model:current-page="searchForm.pageNum"
                v-model:page-size="searchForm.pageSize"
                :page-sizes="[2, 4, 6, 8]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <div>
            <el-dialog v-model="dialogFormVisible" title="商品添加" width="500">
                <el-form :model="form" ref="ruleFormRef" :rules="rules">
                    <el-form-item
                        label="商品类型"
                        prop="kindId"
                        :label-width="formLabelWidth"
                    >
                        <el-radio-group v-model="form.kindId">
                            <el-radio :value="0">实物商品</el-radio>
                            <el-radio :value="1">虚拟商品</el-radio>
                            <el-radio :value="2">卡密/网盘</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item
                        label="商品分类"
                        :label-width="formLabelWidth"
                    >
                        <el-tree-select
                            v-model="form.typeId"
                            :data="typeListTree"
                            check-strictly
                            :render-after-expand="false"
                            style="width: 240px"
                        />
                    </el-form-item>
                    <el-form-item
                        label="商品名称"
                        prop="prodName"
                        :label-width="formLabelWidth"
                    >
                        <el-input v-model="form.prodName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="商品SPU"
                        prop="prodSpu"
                        :label-width="formLabelWidth"
                    >
                        <el-input v-model="form.prodSpu" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="商品品牌"
                        :label-width="formLabelWidth"
                    >
                        <el-select
                            v-model="form.brandId"
                            placeholder="请选择品牌"
                        >
                            <el-option
                                v-for="item in brandListAll"
                                :label="item.brandName"
                                :value="item.brandId"
                                :key="item.brandId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="商品单位"
                        :label-width="formLabelWidth"
                    >
                        <el-select
                            v-model="form.unitId"
                            placeholder="请选择商品单位"
                        >
                            <el-option
                                v-for="item in unitListAll"
                                :label="item.unitName"
                                :value="item.unitId"
                                :key="item.unitId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="商品标签"
                        :label-width="formLabelWidth"
                    >
                        <el-select
                            v-model="form.tagId"
                            placeholder="请选择商品标签"
                        >
                            <el-option
                                v-for="item in tagListAll"
                                :label="item.tagName"
                                :value="item.tagId"
                                :key="item.tagId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="供应商" :label-width="formLabelWidth">
                        <el-select
                            v-model="form.apprId"
                            placeholder="请选择供应商"
                        >
                            <el-option
                                v-for="item in apprListAll"
                                :label="item.apprName"
                                :value="item.apprId"
                                :key="item.apprId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="商品缩略图"
                        prop="prodImage"
                        :label-width="formLabelWidth"
                    >
                        <el-upload
                            class="avatar-uploader"
                            action="http://localhost:10010/shop/type/uploadFile"
                            :show-file-list="false"
                            :headers="headers"
                            :on-success="handleAvatarSuccess"
                        >
                            <img
                                v-if="imageUrl"
                                :src="imageUrl"
                                class="avatar"
                            />
                            <el-icon v-else class="avatar-uploader-icon"
                                ><Plus
                            /></el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item
                        label="商品描述"
                        prop="prodDesc"
                        :label-width="formLabelWidth"
                    >
                        
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false"
                            >放弃</el-button
                        >
                        <el-button
                            type="primary"
                            @click="submitForm(ruleFormRef)"
                        >
                            提交
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
        <el-dialog v-model="attaFormVisible" title="商品附件" width="800">
            <el-form :model="attaForm">
                <el-form-item label="商品轮播图" :label-width="formLabelWidth">
                    <el-upload
                        v-model:file-list="fileList"
                        action="http://localhost:10010/shop/type/uploadFile"
                        list-type="picture-card"
                        :headers="headers"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                    >
                        <el-icon><Plus /></el-icon>
                    </el-upload>

                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="商品视频" :label-width="formLabelWidth">
                    <el-upload
                        v-model:file-list="videoList"
                        class="upload-demo"
                        action="http://localhost:10010/shop/type/uploadFile"
                        :headers="headers"
                        :on-change="handleChange"
                        :before-upload="beforeAvatarUpload"
                    >
                        <el-button type="primary">上传视频</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                作用于商品详情页顶部轮措的视频介绍，最大限制20MB
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="上架时间" :label-width="formLabelWidth">
                    <el-radio-group v-model="attaForm.upType">
                        <el-radio :value="0">立即上架</el-radio>
                        <el-radio :value="1">定时上架</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item
                    label=""
                    :label-width="formLabelWidth"
                    v-if="attaForm.upType == 1"
                >
                    <el-date-picker
                        v-model="attaForm.upTime"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择上架时间"
                    />
                </el-form-item>
                <el-form-item label="定时下架" :label-width="formLabelWidth">
                    <el-switch
                        v-model="attaForm.downType"
                        :active-value="1"
                        :inactive-value="0"
                    />
                </el-form-item>
                <el-form-item
                    label=""
                    :label-width="formLabelWidth"
                    v-if="attaForm.downType == 1"
                >
                    <el-date-picker
                        v-model="attaForm.downTime"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择下架时间"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="attaFormVisible = false">放弃</el-button>
                    <el-button type="primary" @click="onSubmitAddAtta">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <div></div>
        <div>
            <!-- <div id="div1">
                <p>hello,world</p>
            </div> -->
        </div>
    </div>
</template>

<script setup lang="ts">
import WangEditor from "wangeditor";
import { onMounted, ref, reactive } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, type UploadProps } from "element-plus";
import {
    getProdList,
    addProd,
    getTypeSelectTree,
    getBrandListAll,
    getUnitListAll,
    getTagListAll,
    getApprListAll,
    deleteProdAll,
    addProdAtta,
} from "@/api/api";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadUserFile } from "element-plus";

import { useRouter } from 'vue-router';


const router = useRouter();
const editor = ref({});

const fileList = ref<UploadUserFile[]>([]);
const videoList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules<any>>({
    prodName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
    prodSpu: [{ required: true, message: "请输入商品SPU", trigger: "blur" }],
    kindId: [
    {
      required: true,
      message: '请选择商品类型',
      trigger: 'change',
    }],
    prodImage: [{ validator:  (rule: any, value: any, callback: any) => {
        if(imageUrl.value==null || imageUrl.value==''){
            // 提示错误
            callback(new Error('请上传商品图片'));
        }else{
            // 验证通过
            callback();
        }
    }, trigger: "change" }],
});

const prodList = ref([]);
const searchForm = ref({
    pageNum: 1,
    pageSize: 2,
    keyWord: null,
    id: null,
});
const total = ref(0);

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const form = ref({
    apprId: null,
    brandId: null,
    createBy: null,
    createTime: null,
    kindId: null,
    prodId: null,
    prodImage: null,
    prodName: "",
    prodSpu: "",
    prodStatus: null,
    tagId: null,
    typeId: null,
    unitId: null,
    updateBy: null,
    updateTime: null,
});

const typeListTree = ref([]);
const brandListAll = ref([]);
const unitListAll = ref([]);
const tagListAll = ref([]);
const apprListAll = ref([]); // 供应商列表

const imageUrl = ref("");
const headers = {
    token: window.sessionStorage.getItem("token"),
};

const multipleSelection = ref<any[]>([]);

const attaFormVisible = ref(false);
const attaForm = ref({
    downTime: null,
    downType: 0,
    imageList: [],
    prodId: 0,
    prodVideo: null,
    upTime: null,
    upType: 0,
});

// 购买
const handleBuyProd = (row:any) => {
    console.log('handleBuyProd', row);
    let prod = JSON.stringify(row);
    sessionStorage.setItem('buy', prod);
    router.push('/home/buy');
}


// 上传文件之前,校验文件是否为视频文件
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
    console.log("beforeAvatarUpload", rawFile.type);

    if (rawFile.type !== "video/mp4") {
        ElMessage.error("上传文件的视频必须是视频!");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("上传文件不能大于 2MB!");
        return false;
    }
    return true;
};

// 添加商品附件
const onSubmitAddAtta = () => {
    console.log("onSubmitAddAtta", fileList.value);

    // 轮播图数组放入表单
    attaForm.value.imageList = [];
    fileList.value.forEach((item) => {
        console.log("item", item);

        attaForm.value.imageList.push(item.response.data);
    });

    // 商品视频放入表单
    console.log("videoList", videoList.value);

    if (videoList.value.length > 0) {
        attaForm.value.prodVideo = videoList.value[0].response.data;
    }

    // 提交
    addProdAtta(attaForm.value).then((res) => {
        if (res.data.code == 200) {
            attaFormVisible.value = false;
            ElMessage.success("添加商品附件成功");
            loadProdList();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
    console.log("videoList", videoList.value);

    videoList.value = videoList.value.slice(-3);
};

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
    // console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
    console.log("handlePictureCardPreview", uploadFile);

    dialogImageUrl.value = uploadFile.url!;
    dialogVisible.value = true;
};

const handleProd = (row: any) => {
    console.log("row", row);
};

// 点击‘商品附件’时，需要关联商品id
const handleAtta = (row: any) => {
    console.log("row", row);
    attaForm.value.prodId = row.prodId;
    attaFormVisible.value = true;
};

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 表单校验通过，提交表单
            onSubmitAddProd();
        } else {
            // 表单校验失败，打印错误信息
            console.log("error submit!", fields);
        }
    });
};

// 查询
const onQuery = () => {
    loadProdList();
};

const handleDeleteAll = () => {
    console.log("handleDeleteAll", multipleSelection.value);
    //  判断是否选择商品
    if (multipleSelection.value.length == 0) {
        ElMessage.error("请选择要删除的商品");
        return;
    }

    // 确认删除
    ElMessageBox.confirm("数据删除后无法恢复，您确认要删除吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "放弃",
        type: "warning",
    })
        .then(() => {
            //  确认删除
            deleteProdAll(multipleSelection.value).then((res) => {
                if (res.data.code == 200) {
                    ElMessage.success("删除成功");
                    loadProdList();
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
        })
        .catch(() => {
            // 放弃删除
        });
};

const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val;
    console.log("handleSelectionChange", multipleSelection.value);
};

// 提交添加商品
const onSubmitAddProd = () => {
    addProd(form.value).then((res) => {
        if (res.data.code == 200) {
            dialogFormVisible.value = false;
            ElMessage.success("添加商品成功");
            loadProdList();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    //imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    imageUrl.value = response.data;
    form.value.prodImage = imageUrl.value;
};

const resetForm = () => {
    form.value = {
        apprId: null,
        brandId: null,
        createBy: null,
        createTime: null,
        kindId: null,
        prodId: null,
        prodImage: null,
        prodName: "",
        prodSpu: "",
        prodStatus: null,
        tagId: null,
        typeId: null,
        unitId: null,
        updateBy: null,
        updateTime: null,
    };
    imageUrl.value = "";
};

// 添加商品
const handleAddProd = () => {
    console.log("添加商品");
    resetForm();
    dialogFormVisible.value = true;

    //
    // editor.value = new WangEditor("#div1");
    // editor.value.create();
};

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    searchForm.value.pageSize = val;
    loadProdList();
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    searchForm.value.pageNum = val;
    loadProdList();
};

// 获取商品列表
const loadProdList = () => {
    getProdList(searchForm.value).then((res) => {
        if (res.data.code == 200) {
            prodList.value = res.data.data.records;
            total.value = res.data.data.total;
        }
    });
};

// 页面钩子函数
onMounted(() => {

    loadProdList();

    // 获取商品类型树
    getTypeSelectTree().then((res) => {
        if (res.data.code == 200) {
            typeListTree.value = res.data.data;
        }
    });

    // 获取商品品牌列表
    getBrandListAll().then((res) => {
        if (res.data.code == 200) {
            brandListAll.value = res.data.data;
        }
    });

    // 获取商品单位列表
    getUnitListAll().then((res) => {
        if (res.data.code == 200) {
            unitListAll.value = res.data.data;
        }
    });

    // 获取商品标签列表
    getTagListAll().then((res) => {
        if (res.data.code == 200) {
            tagListAll.value = res.data.data;
        }
    });

    // 获取供应商列表
    getApprListAll().then((res) => {
        if (res.data.code == 200) {
            apprListAll.value = res.data.data;
        }
    });
});
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
